﻿using HomeCareLibrary.Core.DataContracts;
using HomeCareLibrary.Core.Dtos;
using HomeCareLibrary.DataAccess;
using HomeCareLibrary.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HomeCareLibrary.AppService.Mappers;

namespace HomeCareLibrary.AppService
{
    public class TasksAppService : AppServiceBase
    {
        private HomeWizardServicesEntities context = new HomeWizardServicesEntities();
        public List<CTRoutineTaskResultDto> GetRoutineTasks(GetRoutineTasksRequest request)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var tipRepository = new Repository<CTRoutineTaskResult>(unitOfWork);
                var queryParameter = string.Format("@dwell_priority_kl_loc='{0}', @feature_string='{1}', @ps_goal_string='{2}', @turn_offs='{3}', @startmonth={4}, @startyear={5}, @requestedmonth={6}, @requestedyear={7}, @user_ID={8}, @home_number={9}", request.DwellPriorityKLLoc, request.FeatureString, request.Goal, request.Turn_Offs, request.StartMonth, request.StartYear, request.RequestedMonth,request.RequestedYear, request.UserId, request.HomeNumber);
                return tipRepository.ExecuteFuntion("[sp_Routinetask]", queryParameter).ToDTOs(); 
            }
        }

        public List<CTTaskDto> GetTasksList(TasksRequest request)
        {
            using(var unitOfWork = new UnitOfWork())
            {
                var taskRepository = new Repository<CTTask>(unitOfWork);
                var queryParameter = string.Format("@paramUserId={0}, @paramHomeNumber={1}, @paramRequestedMonth={2}, @paramRequestedYear={3}",  request.UserId, request.HomeNumber, request.Month, request.Year);
                return taskRepository.ExecuteFuntion("[sp_Task_List]", queryParameter).ToDTOs();
            }
        }

        public Dictionary<String, Object> GetTaskDetail(TaskDetailRequest request)
        {
            string result = string.Empty;
            CTTaskDetailDto taskDetail = null;
            Dictionary<String, Object> dataDictionary = new Dictionary<string, object>();
            using (var unitOfWork = new UnitOfWork())
            {
                var taskDetailRepository = new Repository<CTTaskDetail>(unitOfWork);
                var queryParameter = string.Format("@paramTaskCode='{0}', @returnStatus='{1}', @paramUserId={2}, @paramHomeNumber={3}", request.TaskCode, result, request.UserId, request.HomeNumber);
                taskDetail = taskDetailRepository.ExecuteFuntion("[sp_Display_Task_Details]", queryParameter).FirstOrDefault().ToDTO();
            }
            dataDictionary.Add("Status", result);
            dataDictionary.Add("TaskDetail", taskDetail);
            return dataDictionary;
        }

        public string DoneTask(DoneTaskRequest request)
        {
            var returnData = "Success";
            using (var unitOfWork = new UnitOfWork())
            {
                var taskRepository = new Repository<Done_Tasks>(unitOfWork);
                var task = taskRepository.FirstOrDefault(x => x.task_code == request.TaskCode && x.user_id == request.UserId && x.home_number == request.HomeNumber && x.month == request.Month && x.year == request.Year);

                try
                {
                    if (task != null)
                    {
                        task.status = request.Status;
                        taskRepository.Update(task);
                    }
                    else
                    {
                        var newTask = new Done_Tasks();
                        newTask.task_code = request.TaskCode;
                        newTask.user_id = request.UserId;
                        newTask.home_number = request.HomeNumber;
                        newTask.month = request.Month;
                        newTask.year = request.Year;
                        newTask.status = request.Status;
                        taskRepository.Add(newTask);
                    }
                }
                catch (Exception ex)
                {
                    returnData = "Failed";
                }
            }
            return returnData;
        }

        public string TurnOffTask(TurnOffTaskRequest request)
        { 
            var returnData = "Success";
            using (var unitOfWork = new UnitOfWork())
            {
                var userRepository = new Repository<User_Details>(unitOfWork);
                var user = userRepository.FirstOrDefault(x => x.user_id == request.UserId && x.home_number == request.HomeNumber);
                if (user != null)
                {
                    if (user.turn_offs != string.Empty)
                    {
                        user.turn_offs += "," + request.TaskCode;
                    }
                    else
                    {
                        user.turn_offs = request.TaskCode;
                    }
                    userRepository.Update(user);
                    returnData = "Success";
                }
                else
                {
                    returnData = "invalidUserId";
                }

                return returnData;
            }
        }

        public CRC_Task_DetailsDto CreateCustomTask(CRCTaskRequest request)
        {            
            int customTaskNumber = 1;
            string customTaskCode = string.Empty;
            using (var unitOfWork = new UnitOfWork())
            {
                var repository = new Repository<CRC_Task_Details>(unitOfWork);
                var customTasks = repository.Find(x => x.user_id == request.UserId && x.home_number == request.HomeNumber).OrderByDescending(x=>x.task_code);
                if (customTasks != null && customTasks.Count() > 0)
                {
                    if (customTasks.First().task_code.IndexOf("_") > 0)
                    {
                        customTaskNumber = int.Parse(customTasks.First().task_code.Substring(customTasks.First().task_code.IndexOf("_") + 1)) + 1;
                    }
                }

                customTaskCode = "CRC_" + customTaskNumber.ToString();

                var newCustomTask = new CRC_Task_Details();

                newCustomTask.user_id = request.UserId;
                newCustomTask.home_number = request.HomeNumber;
                newCustomTask.task_code = customTaskCode;
                newCustomTask.image = request.Image;
                newCustomTask.feature_name = request.FeatureName;
                newCustomTask.task_description = request.TaskDescription;
                newCustomTask.timing_months = request.TimingMonths;
                newCustomTask.cycle_timing = request.CycleTiming;
                newCustomTask.priority = request.Priority;
                newCustomTask.benefit_icons = request.BenefitIcons;
                newCustomTask.benefit_names = request.BenefitNames;
                newCustomTask.benefit_content = request.BenefitContent;
                newCustomTask.energy_savings_score = request.EnergySavingsScore;
                newCustomTask.energy_savings_content = request.EnergySavingsContent;
                newCustomTask.cost_score = request.CostScore;
                newCustomTask.cost_content = request.CostContent;
                newCustomTask.type = request.Type;
                
                repository.Add(newCustomTask);
                return newCustomTask.ToDTO();
            }
        }

        public void UpdateCustomTask(CRCTaskRequest request)
        {
            string customTaskCode = string.Empty;
            using (var unitOfWork = new UnitOfWork())
            {
                var repository = new Repository<CRC_Task_Details>(unitOfWork);
                var customTasks = repository.Find(x => x.user_id == request.UserId && x.home_number == request.HomeNumber && x.task_code == request.TaskCode).FirstOrDefault();                
                if (customTasks != null)
                {
                    customTasks.user_id = request.UserId;
                    customTasks.home_number = request.HomeNumber;
                    customTasks.task_code = request.TaskCode;
                    customTasks.image = request.Image;
                    customTasks.feature_name = request.FeatureName;
                    customTasks.task_description = request.TaskDescription;
                    customTasks.timing_months = request.TimingMonths;
                    customTasks.cycle_timing = request.CycleTiming;
                    customTasks.priority = request.Priority;
                    customTasks.benefit_icons = request.BenefitIcons;
                    customTasks.benefit_names = request.BenefitNames;
                    customTasks.benefit_content = request.BenefitContent;
                    customTasks.energy_savings_score = request.EnergySavingsScore;
                    customTasks.energy_savings_content = request.EnergySavingsContent;
                    customTasks.cost_score = request.CostScore;
                    customTasks.cost_content = request.CostContent;
                    customTasks.type = request.Type;

                    repository.Update(customTasks);
                }
            }
        }

        public CRC_Task_DetailsDto GetCustomTask(CRCTaskRequest request)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var taskRepository = new Repository<CRC_Task_Details>(unitOfWork);
                var customTask = taskRepository.Find(x => x.user_id == request.UserId && x.home_number == request.HomeNumber && x.task_code == request.TaskCode).FirstOrDefault();

                return customTask != null ? customTask.ToDTO() : null;
            }
        }

        public bool DeleteEntireFeature(int userId, int homeNumber, string featureString)
        {
            bool returnResult = true;
            using (var unitOfWork = new UnitOfWork())
            {
                var featureRepository = new Repository<User_Details>(unitOfWork);
                var feature = featureRepository.FirstOrDefault(x => x.user_id == userId && x.home_number == homeNumber);
                try
                {
                    if (feature != null)
                    {
                        if(feature.featurestring.Contains(featureString))
                        {
                            string newFeatureString = string.Empty;
                            int startPosition = feature.featurestring.IndexOf(featureString);
                            startPosition = startPosition - 1;
                            int endPosition = feature.featurestring.IndexOf("'",startPosition+1);
                            if(feature.featurestring.Substring(endPosition+1) == ",")
                            {
                                endPosition = endPosition + 1;
                            }                             
                            newFeatureString = feature.featurestring.Substring(0,startPosition);
                            newFeatureString = newFeatureString + feature.featurestring.Substring(endPosition);
                            feature.featurestring = newFeatureString;
                        }
                        featureRepository.Update(feature);
                    }
                    else
                    {
                        returnResult = false;
                    }
                }
                catch (Exception ex)
                {
                    returnResult = false;
                }
            }
            return returnResult;
        }
                
        public List<Benefit_Icon_UrlsDto> GetBenefitIconUrls()
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var repository = new Repository<Benefit_Icon_Urls>(unitOfWork);
                return repository.GetAll().ToList().ToDTOs();
            }
        }

        public object GetRCTaskDetail(string taskCode)
        {                        
            return context.sp_Display_RC_Task_Details(taskCode);
        }
        
        public List<CRC_Task_DetailsDto> GetCustomTasksList(CRCTaskRequest request)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                string userTurnOff = string.Empty;

                var taskRepository = new Repository<CRC_Task_Details>(unitOfWork);
                var userRepository = new Repository<User_Details>(unitOfWork);
                List<CRC_Task_DetailsDto> customTasks = new List<CRC_Task_DetailsDto>();
                customTasks = taskRepository.Find(x => x.user_id == request.UserId && x.home_number == request.HomeNumber).ToDTOs();

                var userDetail = userRepository.FirstOrDefault(x => x.user_id == request.UserId && x.home_number == request.HomeNumber);
                if(userDetail != null)
                {
                    userTurnOff = userDetail.turn_offs;
                    foreach (var task in customTasks)
                    {
                        if (userTurnOff.Contains(task.task_code))
                        {
                            customTasks.Remove(task);
                        }
                    }
                }
                return customTasks;
            }
        }
       
    }    
}
